import componentSetting from '@/setting/componentSetting';
import type { Ref } from 'vue';
import i18n from '@/i18n';

const { t } = i18n.global;

const tableSetting = componentSetting.table;
const apiSetting = tableSetting.apiSetting;
const { pageField, sizeField, listField, totalField } = apiSetting;

interface ParamsType<T> {
	/** 是否分页 默认true */
	isPage?: boolean;
	/** 是否前端自动分页 默认false，true时采用前端分页，false分页采用接口分页 */
	autoPage?: boolean;
	/** 每页条数数组 */
	pageSizes?: number[];
	/** 初始每页条数 */
	pageSize?: number;
	/** 初始当前页 */
	page?: number;
	/** 请求接口 */
	request: Function;
	/** 接口的参数 */
	requestParam?: object;
	/** 请求前执行的函数 */
	beforeRequest?: Function;
	/** 请求后执行的函数 */
	afterRequest?: (tableData: T[]) => void;
	/** 切换页面或每页条数时执行的函数 */
	afterPageChange?: (page: number, pageSize: number) => void;
	/** 接口返回参数处理回调 */
	resFormatter?: (list: T[]) => T[];
}

/**
 * 创建表格参数
 * @param request 请求接口
 * @param requestParam 参数
 * @param isPage 是否分页 默认true
 * @param autoPage 是否前端自动分页 默认false，true时采用前端分页，false分页采用接口分页
 * @param beforeRequest 请求前执行的函数
 * @param afterRequest 请求后执行的函数
 * @param resFormatter 参数处理回调
 * @param T 分页返回数组单项ts定义
 */
export function useTable<T = any>({
	beforeRequest,
	request,
	requestParam,
	resFormatter,
	afterRequest,
	isPage = true,
	autoPage = false,
	pageSizes,
	pageSize,
	page,
	afterPageChange,
}: ParamsType<T>) {
	const tableData = ref<T[]>([]) as Ref<T[]>;
	const loading = ref(false);
	const paginationReactive = reactive({
		page: page || 1,
		pageSize: pageSize || tableSetting.defaultPageSize,
		showQuickJumper: true,
		showSizePicker: true,
		itemCount: 0,
		pageSizes: pageSizes || tableSetting.pageSizes,
		onChange: (page: number) => {
			paginationReactive.page = page;
			afterPageChange && afterPageChange(page, paginationReactive.pageSize);
			!autoPage && getTableList();
		},
		onUpdatePageSize: (pageSize: number) => {
			paginationReactive.pageSize = pageSize;
			paginationReactive.page = 1;
			afterPageChange && afterPageChange(paginationReactive.page, pageSize);
			!autoPage && getTableList();
		},
		prefix({ itemCount }) {
			// return `共 ${itemCount} 条`;
			return t('table.totalNum', { total: itemCount });
		},
	});

	async function getTableList(): Promise<T[]> {
		try {
			beforeRequest && beforeRequest();
			const params = {
				...unref(requestParam),
			};
			if (isPage && !autoPage) {
				params[pageField] = paginationReactive.page;
				params[sizeField] = paginationReactive.pageSize;
			}
			loading.value = true;
			// 数量多时先清空以减少渲染时间
			// if (tableData.value.length > 100) {
			// 	tableData.value = [];
			// }
			// tableData.value = [];
			const { results } = await request(params);

			// 接口返回参数
			let data = [];
			if (isPage && !autoPage) {
				data = JSON.parse(JSON.stringify(results[listField]));
			} else {
				data = JSON.parse(JSON.stringify(results));
			}
			if (resFormatter) {
				tableData.value = (resFormatter(data) as T[]) || [];
			} else {
				tableData.value = data || [];
			}
			if (isPage && !autoPage) {
				paginationReactive.itemCount = results[totalField];
			}
			afterRequest && afterRequest(tableData.value);
			return tableData.value;
		} catch (e) {
			afterRequest && afterRequest([]);
			return [];
		} finally {
			loading.value = false;
		}
	}

	function resetPage() {
		paginationReactive.page = 1;
		paginationReactive.pageSize = pageSize || tableSetting.defaultPageSize;
	}

	return {
		/** loading */
		tableLoading: loading,
		/** 表格数据 */
		tableData,
		/** 分页信息 */
		paginationReactive,
		/** 请求 */
		getTableList,
		/** 将分页信息重置为初始数据 */
		resetPage,
	};
}
